#include "bridge.h"
#include <QSqlDatabase>
#include <QSqlQuery>

#include "databasemanager.h"
Bridge::Bridge(QObject *parent) : QObject(parent)
{
    // udp给串口发数据
    connect(&u, SIGNAL(dataReceivedFromSocket(quint16, QHostAddress, quint16, QByteArray)),
            this, SLOT(UdpToSerial(quint16, QHostAddress, quint16, QByteArray)));
    // tcpclient给串口发数据
    connect(&tc, SIGNAL(dataReceivedFromClient(int, QByteArray)), this, SLOT(TcpClientToSerial(int, QByteArray)));

    connect(&ts, SIGNAL(serverDataReceived(int, QByteArray)), this, SLOT(TcpServerToSerial(int, QByteArray)));


    // 串口给udp发数据
    connect(&s, SIGNAL(dataRecv(QString, QByteArray)), this, SLOT(SerialToUdp(QString, QByteArray)));
    // 串口给tcpClient发送数据
    connect(&s, SIGNAL(dataRecv(QString, QByteArray)), this, SLOT(SerialToTcpClient(QString, QByteArray)));

    connect(&s, SIGNAL(dataRecv(QString, QByteArray)), this, SLOT(SerialToTcpServer(QString, QByteArray)));
}

bool Bridge::connectMysql()
{
    return DatabaseManager::getInstance().connectMysql();
}

void Bridge::init()
{
    s.openAllCOM();
    u.openAllPort();
    tc.openAllPort();

}

void Bridge::UdpToSerial(quint16 localPort, const QHostAddress &senderIp, quint16 senderPort, const QByteArray &data)
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.prepare(QString("SELECT com_nm FROM serialport_config where port_no = %1").arg(localPort));
    if (query.exec())
    {
        while (query.next())
        {
            QString ComName = query.value(0).toString();
            s.sendData(ComName, data);
            qDebug() << localPort << "给串口" << ComName << "发数据" << data;
        }
    }
}

void Bridge::TcpClientToSerial(int logicalClientPort, const QByteArray &data)
{
//    qDebug() << logicalClientPort;
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare(QString("SELECT com_nm FROM serialport_config where port_no = %1").arg(logicalClientPort));
    if (query.exec())
    {
        while (query.next())
        {
            QString ComName = query.value(0).toString();
            s.sendData(ComName, data);
            qDebug() << "端口为：" << logicalClientPort << "tcpClient客户端给串口" << ComName << "发送数据" << data;
        }
    }
}

void Bridge::TcpServerToSerial(int port, const QByteArray &data)
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare(QString("SELECT com_nm FROM serialport_config where port_no = ?"));
    query.bindValue(0, port);
    if (query.exec())
    {
        while (query.next())
        {
            QString ComName = query.value(0).toString();
            s.sendData(ComName, data);
            qDebug() << "端口为：" << port << "tcpServer服务端给串口" << ComName << "发送数据" << data;
        }
    }
}

void Bridge::SerialToUdp(const QString &ComName, const QByteArray &data)
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare(QString("SELECT port_no FROM serialport_config where com_nm = ?"));
    query.bindValue(0, ComName);
    if (query.exec())
    {
        while (query.next())
        {
            quint16 port = query.value(0).toUInt();
            qDebug() << ComName << "通过UDP端口" << port << "发送数据" << data;
            QString ip = "127.0.0.1";
            // 指定发送端口的数据（应该由数据库的peerport读出）
            quint16 peerport = 20007;
            u.sendData(ip, peerport, data);
        }
    }
}

void Bridge::SerialToTcpClient(const QString &ComName, const QByteArray &data)
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare(QString("SELECT port_no FROM serialport_config where com_nm = ?"));
    query.bindValue(0, ComName);
    if (query.exec())
    {
        while (query.next())
        {
            quint16 port = query.value(0).toUInt();
            qDebug() << ComName << "从" << port << "tcpClient读取数据" << data;
            tc.sendData(port, data);
        }
    }
}

void Bridge::SerialToTcpServer(const QString &ComName, const QByteArray &data)
{
    qDebug() << "收到串口数据，ComName:" << ComName << "Data:" << data.toHex();
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QSqlQuery query(dbManager.getDatabase());
    query.clear();
    query.prepare(QString("SELECT port_no FROM serialport_config where com_nm = ?"));
    query.bindValue(0, ComName);
    if (query.exec())
    {
        while (query.next())
        {
            quint16 port = query.value(0).toUInt();

            qDebug() << ComName << "从" << port << "tcpServer读取数据" << data;

            // 只能给特定的客户端端口发送数据
            ts.sendData(port, data);
        }
    }
}
